package com.example.administrator.yuejian_15.model;


import com.example.administrator.yuejian_15.listener.ListListener;
import com.example.administrator.yuejian_15.listener.TListener;
import com.example.administrator.yuejian_15.service.AllService;
import com.example.administrator.yuejian_15.service.Service;

import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class RetrofitBaseModel {
    private AllService allService;
    private Retrofit retrofit;

    public Retrofit getRetrofit(){
        retrofit =new Retrofit.Builder().baseUrl(Service.BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        return retrofit;
    }


    public AllService getAllService() {
        allService=retrofit.create(AllService.class);
        return allService;
    }

    public <T>void callenqueue(
            Call<T> call, final TListener<T> tListener){
        call.enqueue(new Callback<T>() {
            @Override
            public void onResponse(Call<T> call, Response<T> response) {
                if (response.isSuccessful()&&response.body()!=null){
                    tListener.onResponse(response.body());//如果数据成功拿走
                }
                else {
                    tListener.onFail("error1");
                }
            }

            @Override
            public void onFailure(Call<T> call, Throwable t) {
                tListener.onFail("error2");
            }
        });
    }


    public <T>void callenqueueList(Call<List<T>> call,
                                   final ListListener<T> listListener){
        call.enqueue(new Callback<List<T>>() {
            @Override
            public void onResponse(Call<List<T>> call, Response<List<T>> response) {
                if (response.isSuccessful()&&response.body()!=null){
                    listListener.onResponse(response.body());//如果数据成功拿走
                }
                else {
                    listListener.onFail("error shop1");
                }
            }

            @Override
            public void onFailure(Call<List<T>> call, Throwable t) {
                listListener.onFail("error shop2");
            }
        });
    }
}
